package com.bawei.module_documents.manager

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.IIntent
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.module_documents.manager.model.FileService
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 * @Author : 
 * @Time : On 2023/7/29 11:18
 * @Description : FileViewModel
 */
class FileViewModel:BaseViewModel<IIntent>() {
    private val service:FileService by lazy{FileService()}
    private val _states = MutableStateFlow<FileState>(FileState.Init)//MutableStateFlow可变
    val states: StateFlow<FileState>
        get() = _states

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is FileIntent.SelFilesIntent ->  selFiles(it)//请求文件
                    is FileIntent.UploadFilesIntent -> uploadFile(it)//上传文件
                }
            }
        }
    }
    //上传文件
    private fun uploadFile(it: FileIntent.UploadFilesIntent) {
        viewModelScope.launch {
            flow {
                //上传数据的格式：MultipartBody.Part
                val body : RequestBody = RequestBody.create(
                    MediaType.parse("multipart/form-data"), File(it.request.path))
                val part = MultipartBody.Part.createFormData("file", it.request.name, body)
                val uploadDocumentsEntity = service.requestUploadDocuments(part)
                emit(uploadDocumentsEntity)
            }.collect{
                if(it.statusCode == 200)
                _states.value = FileState.UploadSuccess
            }
        }
    }

    private fun selFiles(it: FileIntent.SelFilesIntent) {
        viewModelScope.launch {
            flow {
                 val documentsResponseEntity = service.requestSelDocuments(it.request)
                 emit(documentsResponseEntity)
            }.collect{
                _states.value = FileState.SelFileSuccessState(it.data)
            }
        }
    }


}